package com.pk.android.view;

import java.util.List;

import android.annotation.TargetApi;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.astuetz.PagerSlidingTabStrip;
import com.pk.android.R;
import com.pk.android.model.BaseFragment;
import com.pk.android.model.NavDrawer;
import com.pk.android.model.NavDrawerActivityConfiguration;
import com.pk.android.view.adapter.ScreenSlidePagerAdapter;

// ################################################## //
// ##########   DO NOT EXTEND THIS CLASS   ########## //
// ################################################## //
public abstract class BaseActivity extends ActionBarActivity  {

	private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private List<BaseFragment> mFragments;
    private ActionBarDrawerToggle mDrawerToggle;
    private ActionBar mActionBar;
    private ViewPager mPager;
	private ScreenSlidePagerAdapter mPagerAdapter;
    
	private String ACTIVITY_TITLE = "ACTIVITY_TITLE";
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
   
    private NavDrawerActivityConfiguration navConf ;
   
    protected abstract NavDrawerActivityConfiguration getNavDrawerConfiguration();
    protected abstract void onNavItemSelected( int id );
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // Inflate the menu items for use in the action bar
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main_activity_actions, menu);
	    return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    setContentView(R.layout.activity_main);
	    
	    SetupDrawer();

	}
	
	@TargetApi(14)
	public void SetupDrawer()
	{
	    navConf = getNavDrawerConfiguration();
	       
        setContentView(navConf.getMainLayout());
       
        mTitle = mDrawerTitle = getTitle();
       
        mDrawerLayout = (DrawerLayout) findViewById(navConf.getDrawerLayoutId());
        mDrawerList = (ListView) findViewById(navConf.getLeftDrawerId());
        mDrawerList.setAdapter(navConf.getBaseAdapter());
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
       
        this.initDrawerShadow();
       
        mActionBar = getSupportActionBar();
        
        mActionBar.setDisplayHomeAsUpEnabled(true);
        mActionBar.setHomeButtonEnabled(true);
        
	    
        mDrawerToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,
                getDrawerIcon(),
                navConf.getDrawerOpenDesc(),
                navConf.getDrawerCloseDesc()
                ) {
            @Override
			public void onDrawerClosed(View view) {
            	mActionBar.setTitle(mTitle);
        		if (android.os.Build.VERSION.SDK_INT >= 11)
            		invalidateOptionsMenu();
            }

            @Override
			public void onDrawerOpened(View drawerView) {
        		mActionBar.setTitle(mDrawerTitle);
        		if (android.os.Build.VERSION.SDK_INT >= 11)
            		invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
	}
	
	protected void initDrawerShadow() {
        mDrawerLayout.setDrawerShadow(navConf.getDrawerShadow(), GravityCompat.START);
    }
   
    protected int getDrawerIcon() {
        return R.drawable.ic_drawer;
    }
   
    public void SetupPageViewer(List<BaseFragment> fragments, String title, Boolean hideTabs)
    {
		Intent intent = getIntent();
		String intentTitle = intent.getStringExtra(ACTIVITY_TITLE); 
		mFragments = fragments;
		//## Overwrite pager title with activity's title 
		((TextView)this.findViewById(R.id.main_title)).setText(intentTitle==null ? title:intentTitle);
		
		//## Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setOnPageChangeListener(
        		new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        //## When swiping between pages, select the corresponding tab.
                        //getActionBar().setSelectedNavigationItem(position);
                    	super.onPageSelected(position);
                    	Log.i("onPageSelected", String.format("%d", position));
                    }

					@Override
					public void onPageScrolled(int position,
							float positionOffset, int positionOffsetPixels) {
						// TODO Auto-generated method stub
						super.onPageScrolled(position, positionOffset, positionOffsetPixels);
						Log.i("positionOffset",String.format("%f", positionOffset));
					}
                });

        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(),fragments);
        mPager.setAdapter(mPagerAdapter);
        
        // Bind the tabs to the ViewPager
        PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        tabs.setViewPager(mPager);
        
        if(hideTabs || fragments.size() <= 1)
        	tabs.setVisibility(View.GONE);

    }

    public void SetupPageViewer(List<BaseFragment> fragments, String title)
    {
    	SetupPageViewer(fragments,title, false);
    } 
    
    public void ReplacePage(BaseFragment newFragment, int index)
    {
    	mFragments.set(index, newFragment);
    	mPagerAdapter.notifyDataSetChanged();
    }
    
    public void AddPage(BaseFragment newFragment)
    {
    	mFragments.add(newFragment);
    	mFragments.remove(0);
    	mPagerAdapter.notifyDataSetChanged();
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
   
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if ( navConf.getActionMenuItemsToHideWhenDrawerOpen() != null ) {
            boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
            for( int iItem : navConf.getActionMenuItemsToHideWhenDrawerOpen()) {
                menu.findItem(iItem).setVisible(!drawerOpen);
            }
        }
        return super.onPrepareOptionsMenu(menu);
    }
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        else {
            return false;
        }
    }
   
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ( keyCode == KeyEvent.KEYCODE_MENU ) {
            if ( this.mDrawerLayout.isDrawerOpen(this.mDrawerList)) {
                this.mDrawerLayout.closeDrawer(this.mDrawerList);
            }
            else {
                this.mDrawerLayout.openDrawer(this.mDrawerList);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
 

	@Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }
    
	public void SetPagerCurrentItem(int position)
	{
		mPager.setCurrentItem(position);
	}
	
	public int GetPagerCurrentItem()
	{
		return mPager.getCurrentItem();
	}
	
    protected DrawerLayout getDrawerLayout() {
        return mDrawerLayout;
    }

    protected ActionBarDrawerToggle getDrawerToggle() {
        return mDrawerToggle;
    }
   
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }
   
    public void selectItem(int position) {
        NavDrawer selectedItem = navConf.getNavItems()[position];
       
        this.onNavItemSelected(selectedItem.getId());
        mDrawerList.setItemChecked(position, true);
       
        if ( selectedItem.updateActionBarTitle()) {
            setTitle(selectedItem.getText());
        }
       
        if ( this.mDrawerLayout.isDrawerOpen(this.mDrawerList)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    }
   
    @Override
    @TargetApi(11)
    public void setTitle(CharSequence title) {
        mTitle = title;
    	mActionBar.setTitle(mTitle);
    }

}

 